package org.bbelovic.devel.exercises;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class FootballKata {

    private final String pathToFile;
    private final LineProcessor processor;
    private final LineEvaluator evaluator;

    public FootballKata(final String pathToFile, final LineProcessor processor, final LineEvaluator evaluator) {
        this.pathToFile = pathToFile;
        this.processor = processor;
        this.evaluator = evaluator;
    }

    public String findSmallestSpread() {
        LineEvaluatorOutput output = new LineEvaluatorOutput(Integer.MAX_VALUE, "N/A");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(pathToFile));
            String line = null;
            
            while ((line = br.readLine()) != null) {
                final List<String> tokens = processor.processLine(line);
                final LineEvaluatorInput input = new LineEvaluatorInput(tokens, output.getCurrentLine(), output.getReferenceValue());
                output = evaluator.evaluate(input);
            }
        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        finally {
            close(br);
        }
        return output.getCurrentLine();
    }

    private void close(final Closeable c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}
